package com.tx.admin.characterfetter.controller;

import com.mybatisflex.core.query.QueryWrapper;
import com.tx.admin.characterfetter.pojo.po.CharacterFetter;
import com.tx.admin.detailmodehead.pojo.po.DetailModeHead;
import com.tx.admin.detailmodehead.pojo.vo.DetailModeHeadActorVO;
import com.tx.admin.detailmodehead.service.DetailModeHeadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import lombok.RequiredArgsConstructor;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.tx.core.common.entity.ApiPageResult;
import com.tx.core.common.entity.ApiResult;
import com.tx.core.common.constant.GlobalConstant;
import com.tx.core.common.entity.PageResult;
import com.tx.core.common.entity.SelectIdsDTO;
import com.tx.admin.characterfetter.service.CharacterFetterService;
import com.tx.admin.characterfetter.pojo.dto.CharacterFetterCreateDTO;
import com.tx.admin.characterfetter.pojo.dto.CharacterFetterUpdateDTO;
import com.tx.admin.characterfetter.pojo.dto.CharacterFetterListDTO;
import com.tx.admin.characterfetter.pojo.vo.CharacterFetterVO;
import com.tx.core.common.entity.ImportExcelDTO;
import jakarta.servlet.http.HttpServletResponse;

import java.sql.Wrapper;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 人物关系表 Controller
 * </p>
 *
 * @author sz-admin
 * @since 2025-08-05
 */
@Tag(name =  "人物关系表")
@RestController
@RequestMapping("character-fetter")
@RequiredArgsConstructor
public class CharacterFetterController  {

    private final CharacterFetterService characterFetterService;
    private final DetailModeHeadService detailModeHeadService;

    @Operation(summary = "新增")
    @SaCheckPermission(value = "character.fetter.create")
    @PostMapping
    public ApiResult<Void> create(@RequestBody CharacterFetterCreateDTO dto) {
        characterFetterService.create(dto);
        return ApiResult.success();
    }

    @Operation(summary = "修改")
    @SaCheckPermission(value = "character.fetter.update")
    @PutMapping
    public ApiResult<Void> update(@RequestBody CharacterFetterUpdateDTO dto) {
        characterFetterService.update(dto);
        return ApiResult.success();
    }

    @Operation(summary = "删除")
    @SaCheckPermission(value = "character.fetter.remove")
    @DeleteMapping
    public ApiResult<Void> remove(@RequestBody SelectIdsDTO dto) {
        characterFetterService.remove(dto);
        return ApiResult.success();
    }

    @Operation(summary = "列表查询")
    @SaCheckPermission(value = "character.fetter.query_table")
    @GetMapping
    public ApiResult<PageResult<CharacterFetterVO>> list(CharacterFetterListDTO dto) {
        return ApiPageResult.success(characterFetterService.page(dto));
    }

    @Operation(summary = "关系组合列表查询")
    @PostMapping("createWithHead")
    public ApiResult<Void> createWithHead(@RequestBody List<DetailModeHeadActorVO> dtos) {
        List<CharacterFetter> fettersSave = dtos.stream().map(s -> {
            CharacterFetter fetter = new CharacterFetter();
            fetter.setId(null);
            fetter.setBelongId(s.getBelongId());
            fetter.setType(s.getType());
            fetter.setExt(s.getTargetId());
            fetter.setExt1(s.getRelateDes());
            return fetter;
        }).toList();
        QueryWrapper wrapper = QueryWrapper.create().from(CharacterFetter.class);
        wrapper.eq(CharacterFetter::getBelongId,dtos.get(0).getBelongId())
                .eq(CharacterFetter::getType,dtos.get(0).getType());
        characterFetterService.remove(wrapper);
        characterFetterService.saveBatch(fettersSave);
        return ApiResult.success();
    }

    @Operation(summary = "关系组合列表查询")
    @PostMapping("withHead")
    public ApiResult<PageResult<DetailModeHeadActorVO>> listWithHead(@RequestBody CharacterFetterListDTO dto) {
        PageResult<CharacterFetterVO> page = characterFetterService.page(dto);
        List<Long> collect = page.getRows().stream().map(CharacterFetterVO::getExt).toList();
        //模式
        if (CollectionUtils.isEmpty(collect)){
            return ApiResult.success(new PageResult<>(0,0,0,0,new ArrayList<>()));
        }

        List<DetailModeHead> detailModeHeads = detailModeHeadService.listByIds(collect);
        Map<Long,DetailModeHead> map = Optional.ofNullable(detailModeHeads).orElse(new ArrayList<>()).stream()
                .collect(Collectors.toMap(DetailModeHead::getId,Function.identity()));

        List<DetailModeHeadActorVO> newVos = page.getRows().stream().map(s -> {
            DetailModeHead orDefault = map.getOrDefault(s.getExt(), new DetailModeHead());
            DetailModeHeadActorVO vo = new DetailModeHeadActorVO();
            BeanUtils.copyProperties(orDefault, vo);
            vo.setId(s.getExt());//id以head为准
            vo.setBelongId(s.getBelongId());
            vo.setType(s.getType());
            vo.setTargetId(s.getExt());
            vo.setRelateDes(s.getExt1());
            return vo;
        }).toList();

        PageResult<DetailModeHeadActorVO> actorPage
                = new PageResult<>(page.getCurrent(), page.getLimit(), page.getTotalPage(),page.getTotal(),newVos);
        return ApiResult.success(actorPage);
    }

    @Operation(summary = "详情")
    @SaCheckPermission(value = "character.fetter.query_table")
    @GetMapping("/{id}")
    public ApiResult<CharacterFetterVO> detail(@PathVariable Object id) {
        return ApiResult.success(characterFetterService.detail(id));
    }

    @Operation(summary = "导入")
    @Parameters({
      @Parameter(name = "file", description = "上传文件", schema = @Schema(type = "string", format = "binary"), required = true),
    })
    @SaCheckPermission(value = "character.fetter.import")
    @PostMapping("/import")
    public void importExcel(@ModelAttribute ImportExcelDTO dto) {
        characterFetterService.importExcel(dto);
    }

    @Operation(summary = "导出")
    @SaCheckPermission(value = "character.fetter.export")
    @PostMapping("/export")
    public void exportExcel(@RequestBody CharacterFetterListDTO dto, HttpServletResponse response) {
        characterFetterService.exportExcel(dto, response);
    }
}